package com.zscat.mallplus.pay.interceptor;


import com.alibaba.fastjson.JSON;
import com.jpay.weixin.api.WxPayApiConfig;
import com.jpay.weixin.api.WxPayApiConfigKit;
import com.zscat.mallplus.pay.controller.wxpay.WxPayApiController;
import com.zscat.mallplus.pay.controller.wxpay.WxPayController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class WxPayInterceptor implements HandlerInterceptor {

    private static Logger logger = LoggerFactory.getLogger(WxPayInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                             Object handler) throws Exception {
        if (HandlerMethod.class.equals(handler.getClass())) {
            HandlerMethod method = (HandlerMethod) handler;
            Object controller = method.getBean();
            if (controller instanceof WxPayApiController == false) {
                throw new RuntimeException("控制器需要继承 WxPayApiController");
            }

            try {
                WxPayApiConfig wxPayApiConfig = ((WxPayController) controller).getApiConfig();
                logger.info("微信配置信息:{}", JSON.toJSONString(wxPayApiConfig));
                WxPayApiConfigKit.setThreadLocalWxPayApiConfig(wxPayApiConfig);
                return true;
            } finally {
            }
        }
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o,
                           ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                                Object o, Exception e) throws Exception {
    }
}
